/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 开启时间组件
 *  */
import React, { forwardRef, useState, useEffect } from "react";
import { Row, Col, Icon, Select } from "antd";

const { Option } = Select;

const formatTimes = () => {
  const times = [
    {
      value: "",
      name: "关闭自动启动",
    },
  ];
  for (let h = 0; h <= 23; h++) {
    if (h < 10) {
      h = `0${h}`;
    }
    for (let m = 0; m < 6; m++) {
      times.push({
        value: `${h}:${m}0`,
        name: `${h}:${m}0`,
      });
    }
  }
  return times;
};

const OpenTime = forwardRef((props, ref) => {
  const { value = [], onChange } = props;

  const [times, setTimes] = useState([""]);

  const onAdd = index => {
    if (index == 3) return;
    times.push("");
    onChange && onChange(times);
    setTimes(times);
  };

  const onDelete = index => {
    times.splice(index, 1);
    onChange && onChange(times);
    setTimes(times);
  };

  const onTimeChange = (time, index) => {
    times.splice(index, 1, time || "");
    onChange && onChange(times);
    setTimes(times);
  };

  useEffect(
    () => {
      if (value.length == 0) {
        setTimes([""]);
      } else {
        setTimes(value);
      }
    },
    [value]
  );

  return (
    <div>
      {times.map((time, index) => (
        <Row type="flex" gutter={[10, 0]} key={index}>
          <Col>
            <Select style={{ width: 200 }} value={time} onSelect={t => onTimeChange(t, index)}>
              {formatTimes().map(val => (
                <Option key={val.value} value={val.value}>
                  {val.name}
                </Option>
              ))}
            </Select>
          </Col>
          <Col>
            <Row type="flex" gutter={[20, 0]}>
              {times.length - 1 == index &&
                index < 3 && (
                  <Col>
                    <Icon
                      type="plus-circle"
                      style={{ cursor: "pointer" }}
                      onClick={() => onAdd(index)}
                    />
                  </Col>
                )}
              {index >= 0 &&
                times.length > 1 && (
                  <Col>
                    <Icon
                      type="minus-circle"
                      style={{ cursor: "pointer" }}
                      onClick={() => onDelete(index)}
                    />
                  </Col>
                )}
            </Row>
          </Col>
        </Row>
      ))}
    </div>
  );
});

export default OpenTime;
